import React,{useReducer} from 'react';
import ReactDOM from 'react-dom';
import { HotTable } from '@handsontable/react';
import Handsontable from 'handsontable';
import './columnExpand.css'
import _ from 'lodash';
var MyGlobalData = {
    cells: [[{v:''}, {v:''}]],
    colHeadersTree: [{ id: '0001', name: 'A', isleaf: false, }, { id: '0002', name: 'B', isleaf: false, }]
}
window.MyGlobalData = MyGlobalData
// 对源数据做预处理
MyGlobalData.colHeadersTree.forEach((item,index) => {
    item.layer = 0
    item.expand = false
    item.myId = `${Date.now()}(${index})`
})
// var colTreeDa
export default class App extends React.Component {
    constructor(props) {
        super(props);
        window.$appRoot = this
        this.handsontableData = Handsontable.helper.createSpreadsheetData(10, 10);
        this.hot = React.createRef()

    }

    componentDidMount() {
    }
    render() {
        this.hotSettings = {
            data: getTableData(MyGlobalData.cells),
            rowHeaders: true,
            colHeaders: (column) => {
                let name
                if (MyGlobalData.colHeadersTree[column]) {
                    name = MyGlobalData.colHeadersTree[column].name
                } else {
                    name = ''
                }
                return name
            },
            manualColumnResize: true, // 启用手动列宽调整
            afterGetColHeader(column, TH,) {
                let relative = TH.querySelector('div.relative')
                let icon = relative.querySelector('.wui-table-row-expand-icon')
                if (icon) {
                    icon.remove()
                }                
                let colCell
                if (MyGlobalData.colHeadersTree[column]) {
                    colCell = MyGlobalData.colHeadersTree[column]
                } else {
                    colCell = {}
                }
                if (colCell.name) {
                    let expandDom = createExpandDom(colCell, () => {
                        if (!colCell.expand) {
                            let childNodes =getChildNodes(colCell)
                            childNodes.forEach((item,index) => {
                                item.myId = `${colCell.myId}_${Date.now()}(${index})`
                                item.layer = colCell.layer + 1
                            })
                            MyGlobalData.colHeadersTree.splice(column + 1, 0, ...childNodes)
                            MyGlobalData.cells.forEach(row => {
                                row.splice(column + 1,0,...childNodes.map(ele => ({v:'',myId: colCell.myId})))
                            })                            
                        } else {
                            // 移除列
                            _.remove(MyGlobalData.colHeadersTree, v => v.myId.includes(colCell.myId) && v.myId != colCell.myId)
                            MyGlobalData.cells.forEach(row => {
                                _.remove(row, v => {
                                    v.myId = v.myId ? v.myId : ''
                                    return v.myId.includes(colCell.myId)
                                })
                            })
                        }
                        colCell.expand = !colCell.expand
                        window.$appRoot.hot.current.hotInstance.updateSettings({data:getTableData(MyGlobalData.cells)})
                        window.$appRoot.ColTreeAreaApi.dispatch({colHeadersTree:MyGlobalData.colHeadersTree})
                    })

                    relative.insertBefore(expandDom, relative.firstChild)
                }
            },
            afterRender () {
            },
            afterSelectionEnd(row, column, row2, column2, selectionLayerLevel) {
                let minCol = Math.min(column,column2)
                let maxCol = Math.max(column,column2)
                let colArr = []
                for (let i = minCol; i <= maxCol; i++) {
                    colArr.push(i)
                }
                MyGlobalData.colHeadersTree.forEach((item,index) => {
                    item.lineSelected = colArr.includes(index)
                })
                window.$appRoot.ColTreeAreaApi.dispatch({colHeadersTree:MyGlobalData.colHeadersTree})
            }





        };
        return (
            <div ref={ref => this.mainBox = ref}>
                {/* 存放列树形结构 */}
                <ColTreeArea parentThis={this} onRender={api => {this.ColTreeAreaApi = api}}></ColTreeArea>
                <HotTable
                    id="hot"
                    ref={this.hot}
                    settings={this.hotSettings}
                />
            </div>
        );
    }
}



function createExpandDom({ expand = true, name, isleaf }, onClick = () => { },) {
    let icon = document.createElement('span')
    icon.className = `wui-table-row-expand-icon ${expand ? 'wui-table-row-expanded' : 'wui-table-row-collapsed'} ${isleaf ? 'leafnode' : ''}` // 按钮图标
    icon.innerText = expand ? '-' : '+'
    icon.addEventListener('click', () => {
        onClick()
    })
    return icon
}


function getChildNodes (colCell,column) {
    let data =  [{ id: colCell.id + '_1', name: colCell.name + '_1', isleaf: false, expand: false, pid: '0001' }, { id: colCell.id + '_2', name: colCell.name + '_2', isleaf: false, expand: false, pid: '0001' }]
    return data
}

function ColTreeArea (props) {
    const {onRender = ()=>{},parentThis} = props
    const [state,dispatch] = useReducer((state,action) => ({...state,...action}),{colHeadersTree:[]})
    let {colHeadersTree} = state
    let colHeadersTreeMap = {}
    // 给每条数据添加列序号,另外形成映射
    colHeadersTree.forEach((item,index) => {
        colHeadersTreeMap[item.myId] = item
        item.colIndex = index
    })
    let maxLayer = 0
    // 获取要画线的数据
    let lineData = colHeadersTree.filter(item => item.expand)
    // 找到每条线的结束列索引
    lineData.forEach(item => {
        let mainBoxRect = parentThis.mainBox.getBoundingClientRect()
        let arr = colHeadersTree.filter(ele => ele.myId.includes(item.myId))
        let maxColIndex =Math.max(...arr.map(ele => ele.colIndex))
        let thStartDom = parentThis.hot.current.hotInstance.getCell(-1,item.colIndex)
        let thStartDomRect = thStartDom.getBoundingClientRect()
        let thEndDom = parentThis.hot.current.hotInstance.getCell(-1,maxColIndex)
        let thEndDomRect = thEndDom.getBoundingClientRect()
        let lineWidth = thEndDomRect.right - thStartDomRect.left
        if (item.layer > maxLayer) {
            maxLayer = item.layer
        }
        item.line = {
            lineTop: (item.layer + 1) * 10,
            lineLeft: thStartDomRect.left - mainBoxRect.left,
            lineWidth
        }
    })
    onRender({state,dispatch})
    console.log('lineData',lineData)
    const shousuo = (colCell) => {
        _.remove(MyGlobalData.colHeadersTree, v => v.myId.includes(colCell.myId) && v.myId != colCell.myId)
        MyGlobalData.cells.forEach(row => {
            _.remove(row, v => {
                v.myId = v.myId ? v.myId : ''
                return v.myId.includes(colCell.myId)
            })
        })      
        colCell.expand = !colCell.expand
        window.$appRoot.ColTreeAreaApi.dispatch({colHeadersTree:MyGlobalData.colHeadersTree})  
        window.$appRoot.hot.current.hotInstance.updateSettings({data:getTableData(MyGlobalData.cells)})
    }
    return (
        <div style={{position:'relative',height:`${(maxLayer+1) * 20}px`}}>
           {lineData.map(item => {
               let {lineTop,lineLeft,lineWidth} = item.line
               let {lineSelected} = item
               return <div key={item.myId} className='myLine' style={{position:'absolute',left:`${lineLeft}px`,top:`${lineTop}px`,width:`${lineWidth}px`,height:`${lineSelected ? '2px' : '1px'}`,background:`${lineSelected ? 'blue' : '#CCC'}`}}><span onClick={()=>{shousuo(item)}}>收缩</span></div>
           })}
        </div>
    )
}


function getTableData (cells) {
    return cells.map(item => item.map(ele => ele.v))
}